// 存储鼠标当前位置, left & top
var mouseX = 0;
var mouseY = 0;

// 新建吐槽框，待输入状态
function createTsukkomi(x, y){
    q = computeQ(x, y);
    topHtml = '<td class="arrow">&nbsp;</td>' + 
              '<td class="top" style="width: 90px; height: 20px;">&nbsp;</td>';
    bottomHtml = '<td class="bottom" style="width: 150px; height: 20px;">&nbsp;</td>';
    switch(q){
        // 箭头右上
        case 1: 
            topHtml = '<td class="top" style="width: 90px; height: 20px;">&nbsp;</td>' +
                      '<td class="arrow">&nbsp;</td>';
            bottomHtml = '<td class="bottom" style="width: 150px; height: 20px;">&nbsp;</td>';
            break;
        // 箭头左上
        case 2: 
            topHtml = '<td class="arrow">&nbsp;</td>' +
                      '<td class="top" style="width: 90px; height: 20px;">&nbsp;</td>';
            bottomHtml = '<td class="bottom" style="width: 150px; height: 20px;">&nbsp;</td>';
            break;
        // 箭头左下
        case 3:
            topHtml = '<td class="top" style="width: 150px; height: 20px;">&nbsp;</td>';
            bottomHtml = '<td class="arrowBottom">&nbsp;</td>' +
                         '<td class="bottom" style="width: 90px; height: 20px;">&nbsp;</td>';
            break;
        // 箭头右下
        case 4:
            topHtml = '<td class="top" style="width: 150px; height: 20px;">&nbsp;</td>';
            bottomHtml = '<td class="bottom" style="width: 90px; height: 20px;">&nbsp;</td>' +
                         '<td class="arrowBottom">&nbsp;</td>';
            break;
    }
    adjustedXY = adjustInitXY(x, y, q);
    divX = adjustedXY[0];
    divY = adjustedXY[1];
    id = x + '_' + y;
    // 新增吐槽的纵深
    divZ = 999;
    $('div.tsukkomi').map(function(index, ele){
                if(divZ < $(ele).css('z-index')){
                    divZ = $(ele).css('z-index');
                }
            });
    divZ = parseInt(divZ) + 1;
    tsukkomiHtml = '<div id="'+ id +'" class="tsukkomi" style="position: absolute; width: 190px; left: '+ divX +'px; top: '+ divY +'px; z-index: '+ divZ +'; display: block;">' +
                   '<table border="0" cellspacing="0" cellpadding="0">' +
                   '<tbody>' +
                        '<tr>' +
                            '<td class="leftTop">&nbsp;</td>' +
                            '<td>' +
                                '<table border="0" cellspacing="0" cellpadding="0" class="arrowSet" style="width: 150px;">' +
                                    '<tbody>' +
                                        '<tr>' +
                                        topHtml +
                                        '</tr>' +
                                    '</tbody>' +
                                '</table>' +
                            '</td>' +
                            '<td class="rightTop"> </td>' +
                        '</tr>' +
                        '<tr>' +
                            '<td class="left">&nbsp;</td>' +
                            '<td class="tip" style="width: 150px; height: 0px;">' +
                                '<div class="content">' +
                                    '<textarea spellcheck="false">请吐槽...</textarea>' +
                                    '<button type="button" name="confirm">确定</button>' +
                                    '<button type="button" name="cancel">取消</button>' +
                                '</div>' +
                            '</td>' +
                            '<td class="right">&nbsp;</td>' +
                        '</tr>' +
                        '<tr>' +
                            '<td class="leftBottom">&nbsp;</td>' +
                            '<td>' +
                                '<table border="0" cellspacing="0" cellpadding="0" class="arrowSetBottom">' +
                                    '<tbody>' +
                                        '<tr>' +
                                            bottomHtml +
                                        '</tr>' +
                                    '</tbody>' +
                                '</table>' +
                            '</td>' +
                            '<td class="rightBottom"></td>' +
                        '</tr>' +
                    '</tbody>' +
                '</table>' +
                '<div class="close" style="display: block;">&nbsp;</div>' +
            '</div>';
    $('p.content').after(tsukkomiHtml);
    // 为新吐槽框textarea绑定自适应高度代码
    $('#'+id+' div.content textarea').bind({
                'propertychange':dynamicHeight,
                'input':dynamicHeight
            });
    // 为新吐槽textarea绑定首次获得焦点自动清空内容事件
    $('#'+id+' div.content textarea').bind('focus', function(){
                $(this).val('');
                $(this).unbind('focus');
                // 为'确定'按钮绑定事件
                $(this).parent().children('button[name="confirm"]').bind('click', saveAndAdjust);
            });
    // 为'x'和'取消'按钮绑定上事件
    $('#'+id+' div.close').bind('click', cancelTsukkomi);
    $('#'+id+' button[name="cancel"]').bind('click', cancelTsukkomi);
}
// 根据象限信息及吐槽框的初始默认大小，调整吐槽框的坐标
function adjustInitXY(x, y, q){
    divX = x;
    divY = y;
    switch(q){
        // 箭头右上
        case 1: 
            divX -= 140;
            break;
        // 箭头左上
        case 2: 
            divX -= 50;
            break;
        // 箭头左下
        case 3:
            divX -= 50;
            divY -= 110;
            break;
        // 箭头右下
        case 4:
            divX -= 140;
            divY -= 110;
            break;
    }
    return [divX, divY];
}
// 计算坐标相对于文档中心的"象限"
function computeQ(x, y){
    docWidth = $(document).width();
    docHeight = $(document).height();
    centerX = docWidth/2;
    centerY = docHeight/2;
    xPos = x - centerX;
    yPos = y - centerY;
    // q表示当前点击右键的鼠标位置落在以document正中心为坐标原点的直角坐标系的哪个象限中
    q = 1;
    if(xPos > 0){
        if(yPos > 0){
            q = 4;
        }else{
            q = 1;
        }
    }else{
        if(yPos > 0){
            q = 3;
        }else{
            q = 2;
        }
    }
    return q;
}
// 保存并调整吐槽显示
function saveAndAdjust(){
    if('' == $(this).parent().children('textarea').val()){
        alert('空吐槽犯法啊魂淡！！！');
        return;
    }
    // 1.获取需要的数据，并存入数据库
    tsukkomi = $(this).parents('div.tsukkomi');
    id = tsukkomi.attr('id');
    x = id.split('_')[0];
    y = id.split('_')[1];
    msg = tsukkomi.find('textarea').attr('value');
    // 存入数据库
    path = window.location.pathname.substring('/projects'.length);
    ajaxPost('/save', ['msg='+msg, 'x='+x, 'y='+y, 'path='+path].join('&'), function(result){
                if(typeof result != 'undefined' && result != null && /[0-9]+/.test(result)){
                    $('#'+id).attr('dbId', result);
                }else{
                    alert('Error!'+result);
                }
            });
    // 2.将textArea中内容显示在div中
    tsukkomi.find('div.content').text(msg);
    tsukkomi.css('width', '190px');
    // 3.将'x'按钮的事件绑定为delTsukkomi
    close = tsukkomi.find('div.close');
    close.unbind('click');
    close.bind('click', delTsukkomi);
    // 4.调整tsukkomi位置
    positionAdjust(tsukkomi, x, y);
}
// 输入内容后，调整纵轴坐标，使得箭头对齐吐槽点...
function positionAdjust(tsukkomi, x, y){
    q = computeQ(x, y);
    // 只有3、4象限需要调整
    if(q!=3 && q!=4)return;
    divXY = adjustInitXY(x, y, q);
    divX = divXY[0];
    divY = divXY[1];
    initHeight = 109;
    height = tsukkomi.css('height').replace(/px/, '');
    tsukkomi.css('top', parseInt(divY) + parseInt(initHeight - height) + 'px');
}
// 取消tsukkomi
function cancelTsukkomi(){
    $(this).parents('div.tsukkomi').remove();
}
// 删除tsukkomi
function delTsukkomi(){
    if(window.confirm('确认删除该条吐槽么？')){
        tsukkomiDiv = $(this).parents('div.tsukkomi');
        ajaxPost('/del', 'dbId='+tsukkomiDiv.attr('dbId'), function(result){
                    if(typeof result != 'undefined' && result != null && result != ''){
                        alert(result);
                    }
                });
        tsukkomiDiv.remove();
    }
}
// textarea自适应高度事件代码
function dynamicHeight(){
    height = parseInt($(this).css('height').replace(/px/, ''));
    sHeight = $(this).attr('scrollHeight');
    if(sHeight > 40){
        $(this).css('height', sHeight + 'px');
    }else{
        $(this).css('height', '40px');
    }
}
// ajax提交数据请求
function ajaxPost(url, params, action){
    $.ajax({
        "type":"POST",
        "url":url,
        "data":params,
        "success":action
    });
}
// 初始化tsukkomi
function initTsukkomi(dbId, x, y, msg){
    q = computeQ(x, y);
    topHtml = '<td class="arrow">&nbsp;</td>' + 
              '<td class="top" style="width: 90px; height: 20px;">&nbsp;</td>';
    bottomHtml = '<td class="bottom" style="width: 150px; height: 20px;">&nbsp;</td>';
    switch(q){
        // 箭头右上
        case 1: 
            topHtml = '<td class="top" style="width: 90px; height: 20px;">&nbsp;</td>' +
                      '<td class="arrow">&nbsp;</td>';
            bottomHtml = '<td class="bottom" style="width: 150px; height: 20px;">&nbsp;</td>';
            break;
        // 箭头左上
        case 2: 
            topHtml = '<td class="arrow">&nbsp;</td>' +
                      '<td class="top" style="width: 90px; height: 20px;">&nbsp;</td>';
            bottomHtml = '<td class="bottom" style="width: 150px; height: 20px;">&nbsp;</td>';
            break;
        // 箭头左下
        case 3:
            topHtml = '<td class="top" style="width: 150px; height: 20px;">&nbsp;</td>';
            bottomHtml = '<td class="arrowBottom">&nbsp;</td>' +
                         '<td class="bottom" style="width: 90px; height: 20px;">&nbsp;</td>';
            break;
        // 箭头右下
        case 4:
            topHtml = '<td class="top" style="width: 150px; height: 20px;">&nbsp;</td>';
            bottomHtml = '<td class="bottom" style="width: 90px; height: 20px;">&nbsp;</td>' +
                         '<td class="arrowBottom">&nbsp;</td>';
            break;
    }
    adjustedXY = adjustInitXY(x, y, q);
    divX = adjustedXY[0];
    divY = adjustedXY[1];
    id = x + '_' + y;
    // 新增吐槽的纵深
    divZ = 999;
    $('div.tsukkomi').map(function(index, ele){
                if(divZ < $(ele).css('z-index')){
                    divZ = $(ele).css('z-index');
                }
            });
    divZ = parseInt(divZ) + 1;
    tsukkomiHtml = '<div id="'+ id +'" class="tsukkomi" style="position: absolute; width: 190px; left: '+ divX +'px; top: '+ divY +'px; z-index: '+ divZ +'; display: block;" dbId="'+ dbId +'">' +
                   '<table border="0" cellspacing="0" cellpadding="0">' +
                   '<tbody>' +
                        '<tr>' +
                            '<td class="leftTop">&nbsp;</td>' +
                            '<td>' +
                                '<table border="0" cellspacing="0" cellpadding="0" class="arrowSet" style="width: 150px;">' +
                                    '<tbody>' +
                                        '<tr>' +
                                        topHtml +
                                        '</tr>' +
                                    '</tbody>' +
                                '</table>' +
                            '</td>' +
                            '<td class="rightTop"> </td>' +
                        '</tr>' +
                        '<tr>' +
                            '<td class="left">&nbsp;</td>' +
                            '<td class="tip" style="width: 150px; height: 0px;">' +
                                '<div class="content">' +
                                    msg +
                                '</div>' +
                            '</td>' +
                            '<td class="right">&nbsp;</td>' +
                        '</tr>' +
                        '<tr>' +
                            '<td class="leftBottom">&nbsp;</td>' +
                            '<td>' +
                                '<table border="0" cellspacing="0" cellpadding="0" class="arrowSetBottom">' +
                                    '<tbody>' +
                                        '<tr>' +
                                            bottomHtml +
                                        '</tr>' +
                                    '</tbody>' +
                                '</table>' +
                            '</td>' +
                            '<td class="rightBottom"></td>' +
                        '</tr>' +
                    '</tbody>' +
                '</table>' +
                '<div class="close" style="display: block;">&nbsp;</div>' +
            '</div>';
    $('p.content').after(tsukkomiHtml);
    // 为'x'按钮绑定上事件
    $('#'+id+' div.close').bind('click', delTsukkomi);
    tsukkomi = $('#'+id);
    tsukkomi.css('width', '190px');
    positionAdjust(tsukkomi, x, y);
}
$(document).ready(function(){ 
    // 实时更新鼠标坐标值
    $(document).mousemove(function(e) {
        mouseX = e.pageX; 
        mouseY = e.pageY;
    });
    // 创建自定义的contextMenu
    $(document).contextMenu('myMenu', {
        bindings: {
            'open': function(t) {
                createTsukkomi(mouseX, mouseY);
            }
        }
    });
    (function(){
        if(ts.length > 0)
        for(var i = 0;i < ts.length; i++){
            initTsukkomi(ts[i][0], ts[i][1], ts[i][2], ts[i][3]);            
        }
     })();
});

